from django.http import JsonResponse
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt

from content.models import PostModel, CataLogModel
from user.models import BBSUser, CommentModel
from content.forms import PostEditForm
from bbs.utils import get_verify_num, set_verify_num


def post_detail(request, post_id):
    post = get_object_or_404(PostModel, pk=post_id)
    # 记录已浏览
    if request.user.is_authenticated:
        post.viewed.add(request.user)

    # 获取评论
    comments = CommentModel.objects.filter(post=post)
    return render(request, 'post/detail.html', {
        'post': post,
        'catalog_id': post.catalog.pk,
        'comments': comments,
        'title': post.title,
        'page_name': 'jie'
    })


@login_required(login_url='/user/login/')
def edit_post(request, post_id=None):
    user = request.user
    if not post_id:
        context = {
            'is_add': True,
            'title': '发表新帖'
        }
    else:
        context = {
            'is_add': False,
            'post': get_object_or_404(PostModel, pk=post_id),
            'title': '编辑帖子'
        }

    if request.method == 'GET':
        context['ver_code'] = set_verify_num(request)
        return render(request, 'post/edit.html', context)

    form = PostEditForm(request.POST, instance=context.get('post'))
    ret_dict = {'status': 0, 'msg': ''}

    if form.is_valid():
        if get_verify_num(request) != int(form.cleaned_data['ver_code']):
            ret_dict['status'] = 2
            ret_dict['msg'] = "验证码错误"
            return JsonResponse(ret_dict)

        try:
            catalog = CataLogModel.objects.get(pk=int(form.cleaned_data['catalog_id']))
        except (CataLogModel.DoesNotExist, ValueError):
            ret_dict['status'] = 3
            ret_dict['msg'] = '栏目不存在，请重新选择'
            return JsonResponse(ret_dict)

        # TODO: 用户新建帖子或者修改帖子所属栏目之后给版主发送通知
        if context['is_add']:
            if int(form.cleaned_data['reward']) > user.coin:
                ret_dict['status'] = 4
                ret_dict['msg'] = "剩余金币不足，无法发布悬赏帖子，请坚持每日签到吧"
                return JsonResponse(ret_dict)
            post = form.save(commit=False)
            post.catalog = catalog
            post.creator = user
            # 从账户扣除悬赏金币
            user.coin -= post.reward

            user.save()
            post.save()
            ret_dict['msg'] = '发帖成功'
        else:
            post = form.save(commit=False)
            post.catalog = catalog
            post.save()
            ret_dict['msg'] = '修改成功'
        ret_dict['action'] = reverse('post_detail', args=(post.pk,))
        return JsonResponse(ret_dict)
    else:
        ret_dict['status'] = 3
        ret_dict['msg'] = "信息填写格式有误，请重新检查"

    return JsonResponse(ret_dict)


@login_required
@csrf_exempt
def collection_status(request, post_id):
    post = get_object_or_404(PostModel, pk=post_id)
    return JsonResponse({
        'data': {'collection': bool(post.like.filter(pk=request.user.pk))},
        'msg': '',
        'status': 0
    })


@login_required
def post_action(request, post_id):
    action = request.POST.get('action')
    try:
        status = bool(int(request.POST.get('status')))
    except ValueError:
        return JsonResponse({}, status=400)

    post = get_object_or_404(PostModel, pk=post_id)
    if action == 'like':
        if status:
            post.like.add(request.user)
        else:
            post.like.remove(request.user)
    elif action == 'closed':
        post.is_closed = status
    elif action == 'top':
        post.is_top = status
    elif action == 'cream':
        post.is_cream = status
    elif action == 'delete':
        catalog = post.catalog
        post.delete()
        return JsonResponse({'status': 0, 'msg': '删除成功', 'action': reverse('catalog', args=(catalog.pk,))})

    post.save()
    return JsonResponse({'status': 0, 'msg': ''})
